import json
from pkgutil import get_data

from flask_restful import Resource,reqparse,request
from comment.models.index import *
from comment.utils.data2dict import datalist2dict
from comment.utils.redis_client import rc as redis_client

# 商品分类的资源类
class Shopping_Category(Resource):

    def get(self):
        # 从redis读取数据
        data_cache = redis_client.get("index_category")
        if data_cache:  #如果redis有缓存数据，则直接返回redis中的缓存数据
            return json.loads(data_cache)
        else:#如果redis中没有数据，则从MySQL查询数据，再写入redis
            rq = reqparse.RequestParser()  #传入parent_id进行参数校验
            rq.add_argument('parent_id', required=True, type=int,default=0)
            req = rq.parse_args()
            data = self.getData(req.parent_id)
            if data:
                for item in data:
                    item.update({'list':''})
                    data_second = self.getData(item['id'])
                    item['list'] = data_second
                    for item1 in data_second:
                        item1.update({'list':''})
                        data_third = self.getData(item1['id'])
                        item1['list'] = data_third
                # 把查询到的数据写入redis
                redis_client.setex("index_category", 3600*24, json.dumps(data))
                return data
            else:
                return {'message': 'none'}

    @staticmethod
    def getData(parent_id):
        res = Category.query.with_entities(Category.id, Category.parent_id, Category.name) \
            .filter(Category.parent_id == parent_id).order_by(Category.sort.asc()).all()

        if res:
            return datalist2dict(res)
        else:
            return 'none'

class Dict_test(Resource):
    def get(self):
        # 取多条数据（所有字段）
        res = Category.query.with_entities(Category.id,Category.name).filter(Category.parent_id==0).all()

        if res:
            return datalist2dict(res)
        else:
            return 'none'

#首页新品推荐的资源类
class Shopping_HomeNewProduct(Resource):
    def get(self):
        res = HomeNewProduct.query.join(Product,HomeNewProduct.product_id==Product.id)\
        .with_entities(Product.id,Product.default_pic,Product.product_name,Product.rel_category3_id,
                       Product.price).order_by(HomeNewProduct.sort.asc()).limit(10).all()
        if res:
            return datalist2dict(res)
        else:
            return {'message':'none'}

# 人气热搜的资源类
class Shopping_HomeRecommendProduct(Resource):
    def get(self):
        data_cache = redis_client.get("index_HomeRecommendProduct")
        if data_cache:
            return json.loads(data_cache)
        else:
            res = HomeRecommendProduct.query.join(Product,HomeRecommendProduct.product_id==Product.id)\
            .with_entities(Product.id,Product.default_pic,Product.product_name,Product.rel_category3_id,
                       Product.price).order_by(HomeRecommendProduct.sort.asc()).limit(10).all()
            if res:
                data = datalist2dict(res)
                # 将查询到的数据写入redis
                redis_client.setex("index_HomeRecommendProduct", 3600*24, json.dumps(data))
                return data
            else:
                return {'message': 'none'}

# 专题的资源类
class Shopping_RecommendSubject(Resource):
    def get(self):
        data_cache = redis_client.get("index_RecommendSubject")
        # 从redis读取数据
        if data_cache:
            return json.loads(data_cache)
        else:
            res = CmsSubject.query.filter(CmsSubject.show_status == 1).all()
            if res:
                data = datalist2dict(res)
                for i in range(len(data)):
                    res_product = (CmsSubjectProductRelation.query.join \
                                   (Product,CmsSubjectProductRelation.product_id==Product.id).filter \
                                   (CmsSubjectProductRelation.subject_id==data[i]['id']).with_entities \
                                   (Product.id,Product.default_pic,Product.price,Product.product_name,Product.rel_category3_id)\
                        .limit(10).all())
                    if res_product:
                        data[i]['productList'] = datalist2dict(res_product)
                    else:
                        data[i]['productList'] = ''
                # 将查询到的数据写入redis
                redis_client.setex("index_RecommendSubject", 3600*24, json.dumps(data))
                if len(data) > 0:
                    print(data)
                    return data
                return data
            else:
                return {'message': 'none'}

